import React, { useState, useEffect } from 'react'
import './userTable.css'
import axios from 'axios'
import { message, Switch } from 'antd'
import { getToken } from '../../api/user'

// 添加样式
export default function Home() {
  const [userData, setUserData] = useState([])
  const [loading, setLoading] = useState(true)
  const [updatingUser, setUpdatingUser] = useState(null) // 跟踪正在更新的用户ID，防止重复操作

  // 模拟用户数据（API调用失败时的备用数据）
  // const mockUserData = [
  //   { id: '1', userCode: '1', name: 'admin', nickname: 'xff', gender: '男', phone: '', houseCount: 1, isActive: false },
  //   { id: '2', userCode: '2', name: 'test2', nickname: 'xff', gender: '男', phone: '', houseCount: 0, isActive: false },
  //   { id: '3', userCode: '3', name: 'levi', nickname: '好客_225022', gender: '男', phone: '', houseCount: 1, isActive: true },
  //   { id: '4', userCode: '4', name: 'akeman', nickname: '好客_13420', gender: '男', phone: '', houseCount: 0, isActive: true }
  // ]

  // 获取用户列表数据
  const fetchUserList = async () => {
    try {
      setLoading(true)
      const token = getToken()

      if (!token) {
        console.error('未找到用户token')
        message.error('未登录或登录已过期，请重新登录')
        setUserData(mockUserData)
        return
      }

      const response = await axios.get('http://localhost:8080/admin/users', {
        headers: {
          'authorization': token,
          'accept': 'application/json'
        }
      })

      console.log('API响应:', response)

      if (response.data?.status === 200 || response.data?.status === 0) {
        const users = response.data?.body || []
        const formattedUsers =
          users.length > 0
            ? users.map(user => formatUserData(user))
            : mockUserData.map(user => formatUserData(user))
        setUserData(formattedUsers)
      } else {
        const formattedMockData = mockUserData.map(user => formatUserData(user))
        setUserData(formattedMockData)
        message.error(response.data?.description || '获取用户数据失败，显示模拟数据')
      }
    } catch (error) {
      setUserData(mockUserData)
      message.error(error.response?.data?.description || '网络请求失败，显示模拟数据')
    } finally {
      setLoading(false)
    }
  }

  // 处理开关状态变化
  const handleToggle = async (e, userData) => {
    // 兼容两种调用方式：传统checkbox事件和直接传入checked状态
    e.preventDefault?.()
    e.stopPropagation?.()

    let userCode = userData.userCode || userData.id || userData.name || userData.nickname
    if (!userCode) userCode = Math.floor(Math.random() * 1000).toString()
    userCode = String(userCode)

    if (!userCode || userCode === 'undefined' || userCode === 'null' || userCode === '') {
      message.error('用户ID无效，无法执行操作')
      return
    }

    if (updatingUser === userCode) return
    setUpdatingUser(userCode)

    // 对于新的Switch组件，userData.isActive已经是更新后的状态
    const newStatus = userData.isActive
    const disabled = !newStatus

    try {
      const token = getToken()
      if (!token) {
        message.error('未登录或登录已过期，请重新登录')
        return
      }

      // 本地立即更新
      setUserData(prevData =>
        prevData.map(user =>
          (user.name === userData.name || user.nickname === userData.nickname)
            ? { ...user, isActive: newStatus }
            : user
        )
      )

      const response = await axios.patch(
        `http://localhost:8080/admin/users/${userCode}`,
        { disabled: disabled },
        {
          headers: {
            'Content-Type': 'application/json',
            'authorization': token
          }
        }
      )

      const isSuccess =
        response.data?.status === 200 ||
        response.data?.status === 0 ||
        response.data?.description?.includes('成功')

      if (isSuccess) {
        setTimeout(() => fetchUserList(), 200)
      } else {
        message.error('用户状态更新失败，可能未保存成功')
        setTimeout(() => fetchUserList(), 100)
      }
    } catch (error) {
      console.error('更新用户状态失败:', error)
      message.error('用户状态更新失败，请重试')
      setTimeout(() => fetchUserList(), 100)
    } finally {
      setUpdatingUser(null)
    }
  }

  useEffect(() => {
    fetchUserList()
  }, [])

  // 格式化用户数据
  const formatUserData = user => {
    let isActive = user.isActive !== undefined ? user.isActive : true
    if (user.disabled !== undefined) {
      const disabledValue =
        typeof user.disabled === 'string'
          ? user.disabled.toLowerCase() === 'true'
          : user.disabled
      isActive = !disabledValue
    } else if (user.status !== undefined) {
      isActive =
        user.status === 1 || user.status === 'normal' || user.status === 'active'
    }

    let id = user.id || user.userId || user.code || user.userCode
    if (!id) id = user.name || user.nickname || Math.floor(Math.random() * 1000).toString()

    return {
      id: String(id),
      userCode: String(id),
      name: user.name || user.username || user.userName || '',
      nickname: user.nickname || user.nickName || '',
      gender:
        user.gender === '1' || user.gender === 1 || user.gender === '男'
          ? '男'
          : user.gender === '0' || user.gender === 0 || user.gender === '女'
          ? '女'
          : '未知',
      phone: user.phone || user.phoneNumber || '',
      houseCount: user.houseCount || user.houseNum || 0,
      isActive: isActive
    }
  }

return (
  <div className="home-container">
    <div className="header-section">
      <h2 className="page-title">用户管理</h2>
    </div>

    <div className="table-wrapper">
      <table className="user-table">
        <thead>
          <tr>
            <th>姓名</th>
            <th>昵称</th>
            <th>性别</th>
            <th>电话</th>
            <th>房源数量</th>
            <th>是否启用</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          {userData.length > 0 ? (
            userData.map((user, index) => {
              const formattedUser = formatUserData(user)
              return (
                <tr key={formattedUser.id || index}>
                  <td>{formattedUser.name}</td>
                  <td>{formattedUser.nickname}</td>
                  <td>
                    <span className="gender-tag">{formattedUser.gender}</span>
                  </td>
                  <td>{formattedUser.phone}</td>
                  <td>{formattedUser.houseCount}</td>
                  <td>
                    <span
                      className={
                        formattedUser.isActive
                          ? 'status-active'
                          : 'status-disabled'
                      }
                    >
                      {formattedUser.isActive ? '正常' : '已禁用'}
                    </span>
                  </td>
                  <td>
 
                     <Switch 
                     checked={formattedUser.isActive}
                      onChange={(checked) => {
                        // 创建一个模拟的event对象以兼容handleToggle函数
                        const mockEvent = {
                          preventDefault: () => {},
                          stopPropagation: () => {}
                        };
                        handleToggle(mockEvent, { ...formattedUser, isActive: checked });
                      }}
                      disabled={
                        updatingUser === formattedUser.userCode ||
                        updatingUser === formattedUser.id
                      }
                      // checkedChildren="启用"
                      // unCheckedChildren="禁用"
                      size="big"
                      style={{
                        fontSize: '12px',
                        height: '24px'
                      }}/>
                  </td>
                </tr>
              )
            })
          ) : (
            <tr>
              <td colSpan="7" style={{ textAlign: 'center', padding: '20px' }}>
                暂无用户数据
              </td>
            </tr>
          )}
        </tbody>
      </table>
    </div>
  </div>
)

}